package show.me.the.money.accredit;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


public class ManageUnit implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	private String id;
	private String name;
	private String parentId;
	private String type;
	private List<String> subUnits = new ArrayList<String>();
	private HashMap<String,RoleAlias> roles = new HashMap<String,RoleAlias>();
	private HashMap<String,Object> properties = new HashMap<String,Object>();
	
	
	public ManageUnit(String id){
		this.id = id;
	}
	
	public String getId(){
		return id;
	}
	
	public String getName(){
		return name;
	}
	
	public void setName(String nm){
		name = nm;
	}
	
	public String getType(){
		return type;
	}
	
	public void setType(String tp){
		type = tp;
	}
	
	public Object getProperty(String nm){
		return properties.get(nm);
	}
	
	public void setProperty(String nm,Object v){
		properties.put(nm, v);
	}
	
	public void setParentId(String id){
		parentId = id;
	}
	
	public ManageUnit getParent(){
		return Organization.instance().getUnit(parentId);
	}
	
	public void addSubUnit(String id){
		subUnits.add(id);
	}
	
	public void addRole(String urid,RoleAlias ur){
		roles.put(urid,ur);
	}
	
	public List<ManageUnit> getSubUnits(){
		List<ManageUnit> ls =  new ArrayList<ManageUnit>();
		for(String id : subUnits){
			ls.add(Organization.instance().getUnit(id));
		}
		return ls;
	}
	
	public Role getRole(String id){
		if(roles.containsKey(id)){
			RoleAlias rid = roles.get(id);
			RolesController rc = RolesController.instance();
			if(rc.hasRole(rid.getRef())){
				//String roleId = this.id + RolesController.R_SIGN + rid.getRef();   // A-system
				String roleId = rid.getSign();
				Role r = RolesController.instance().getRole(roleId);
				r.setManageUnit(this);
				r.setRoleAlias(rid);
				return r;
			}
		}
		return null;
	}
	
	public List<Role> getRoles(){
		List<Role> ls = new ArrayList<Role>();
		RolesController rc = RolesController.instance();
		for(Iterator<String> it = roles.keySet().iterator();it.hasNext();){
			String key = it.next();
			//String roleId = this.id + RolesController.R_SIGN + roles.get(key).getRef();
			String roleId = roles.get(key).getSign();
			Role r = rc.getRole(roleId);
			r.setManageUnit(this);
			ls.add(r);
		}
		return ls;
	}
	
	public HashMap<String,Object> data(){
		HashMap<String,Object> rec = new HashMap<String,Object>();
		rec.put("id", this.id);
		rec.put("name", this.name);
		for(Iterator<String> it = properties.keySet().iterator();it.hasNext();){
			String key = it.next();
			Object v = properties.get(key);
			rec.put(key, v);
		}
		return rec;
	}
}
